/**
 * Created by leiweibo on 8/12/15.
 */
var app = angular.module('baseservice', []);



var getBaseUploader = function(array, brwoswerBtnStr, container, percentage, pos) {
  var options = {
    'expiration': Math.floor(new Date().getTime() / 1000) + 86400,
    bucket: 'vistrack-attach-prd',
    'save-key': '/{filemd5}{.suffix}'
  };
  // 查看更多参数：http://docs.upyun.com/api/form_api/#表单API接口简介
  var policy = window.btoa(JSON.stringify(options));
  // 从 UPYUN 用户管理后台获取表单 API
  //  var form_api_secret = 'uWXYXiFzo9SwavwderRAIyYJCjg=';
  var form_api_secret = '5ri+TpAfi0lw+O9eaH9PBMYoSHI=';
  // 计算签名
  var signature = md5(policy + '&' + form_api_secret);
  var url_prefix = "http://" + options.bucket + ".b0.upaiyun.com";
  var uploader = new plupload.Uploader({
    runtimes: 'html5,flash,silverlight,html4',
    browse_button: brwoswerBtnStr, // you can pass in id...
    container: document.getElementById(container),
    flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf',
    silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap',
    multi_selection:false,
    url: 'http://v0.api.upyun.com/' + options.bucket,

    multipart_params: {
      'Filename': '${filename}', // adding this to keep consistency across the runtimes
      'Content-Type': '',
      'policy': policy,
      'signature': signature
    },

    init: {
      PostInit: function () {
        //do nothing here.
      },

      FilesAdded: function (up, files) {
        plupload.each(files, function (file) {
          uploader.start();
        });
      },

      UploadProgress: function (up, file) {
        if ($("#" + percentage) && $("#" + percentage).size() > 0) {
          $("#" + percentage).text(file.percent + "%");
        } else {
          $('#percentage').text(file.percent + "%");
        }

      },

      FileUploaded: function (up, file, info) {
        var response = JSON.parse(info.response);
        array[pos] = url_prefix + response.url;
        console.log(array);
      },

      Error: function (up, err) {
        $("#" + percentage).text("上传失败");
      }
    }
  });
  uploader.init();
}

app.factory('BaseService', function($http) {
  //var url = "http://localhost:3000/api"; //localhost
  var url = "http://120.27.196.132:3000/api"; //aliyun
  var configUpyun = function() {
    app.config(['upyunProvider',function(upyunProvider) {
      upyunProvider.config({
        form_api_secret: '5ri+TpAfi0lw+O9eaH9PBMYoSHI=',
        bucket: 'vistrack-attach-prd'
      });
    }]);
  }
  return {
    baseUrl: url,
    configUpyun: configUpyun,
    getBaseUploader: getBaseUploader
  }
});
